###############################################################################
# SNOW.R
#
# Distributes simulations to different CPUs
#
# Last edited: 16 Feb 2016 by Roni 
###############################################################################

#########################
## ESTIMATION STRATEGY ##
#########################
##  Rule              Number      Burn-in     run-time     number of runs     type of average
## Sticker              4           75          1             500               ensemble
## Governator           3           75          1             500               ensemble
## Hunting Governator   8           75          1             500               ensemble
## Hunter               7          100         500             1                time
## Aggregator           2           75          1             500               ensemble


rm(list = ls(all = TRUE))

library(plyr)
set.seed(539139152)

################################
# GET THE INPUT MATRIX AS LIST #
################################

repeat.single.row <- function(x, rep.vector) {
matrix(kronecker(as.matrix(x), rep(1, rep.vector)), nrow=rep.vector)
}

repeat.rows <- function(x, rep.vector) {
   x.list <- alply(x, 1, NULL)
    output <- do.call(rbind, mapply(repeat.single.row, x.list, rep.vector, SIMPLIFY=FALSE))
    return(output)
}

## # set number of simulations, runs, voters and parties
N <- 5000

input <- data.frame(parties=sample(2:8, (N*5), TRUE),
                   discount=runif((N*5), 0, 1),
                   memory=2, 
                   aspiration=.9,
                   alpha=runif((N*5), 0, 1),
                   sd.distance=runif((N*5), 0, 2),
                   rules=rep(c(7,2,3,8, 4), each=N)
                  )

input$experiment <- seq_len(nrow(input))
input$Nruns <- ifelse(input$rules==7, 1, 500)
input$no.evo.length <- ifelse(input$rules==7, 600, 75)
input$evo.burn.in <- 0 
input <- repeat.rows(input, input$Nruns)
input <- as.data.frame(cbind(input, sample(seq_len(999999999), nrow(input), FALSE)))
names(input) <- c("parties", "discount", "memory", "aspiration","alpha","sd.distance", "rule",
                  "experiment", "Nruns", "no.evo.length", "evo.burn.in", "seed")
input$num <- unlist(tapply(input$Nruns, input$experiment, function (x) seq_len(unique(x))))
input.list <- split(input, input$experiment)
save(input.list, file="input.list.Rdata")